neutron.setTitle("Settings")
neutron.setMinSize(540, 300)
neutron.getInfo((data) => {
    if (data[0]["h"] < 300) {
        neutron.setWinSize(540, 300)
    }
});

NEU_DATA = {
    "page": 0
}

window.onload = () => {
    neutron.loadData((data) => {
        if (data[0] == undefined) {
            return
        }
        ch_page(data[0]["page"]) // 切换页面
    })
}

function ch_page(id) {
    // 设置按钮与页面
    document.getElementsByClassName("bar_choose")[0].classList.remove("bar_choose")
    document.getElementById("left_bar").getElementsByTagName("button")[id].classList.add("bar_choose")
    document.getElementsByClassName("page_show")[0].classList.remove("page_show")
    document.getElementById("page_" + id).classList.add("page_show")
    NEU_DATA["page"] = id
    neutron.saveData(NEU_DATA) // 保存当前页面id
    if (id == 5) { // 加载用户数据
        load_users()
    }
    if (id == 6) { // 加载插件数据
        load_plugins()
    }
}

function open_cfg() {
    neutron.createIframeWin("Editor", "/api/plugin/editor/iframe/index.html#" + WORK_DIR + "/config/config.toml")
}

css_list = [
    "",
    "background: linear-gradient(45deg, #1884ff, #0062d1);",
    "background: linear-gradient(to right, rgb(17, 153, 142), rgb(56, 239, 125));",
    "background: linear-gradient(to right, #ff7e5f, #feb47b);",
    "background: linear-gradient(to right, rgb(0, 159, 255), rgb(236, 47, 75));",
    "background: linear-gradient(to right, #6a3093, #a044ff);",
    "background-image:url('" + API_PATH + "/bg_image/" + Math.random(1, 1000000) + "');background-size:cover;background-position: center;background-repeat:no-repeat;"
]

function change_bg(id) { // 更改背景
    window.parent.document.getElementById("win_app").setAttribute("style", css_list[id])
    var xhr = new XMLHttpRequest();
    var url = new URLSearchParams();
    url.append("css", css_list[id])
    xhr.open("POST", API_PATH + "/change_bg?" + url.toString(), true);
    xhr.send();
}

function change_bg_custom() { // 自定义背景
    neutron.createIframeWin("Save", "/api/plugin/filemanager/iframe/index.html?" + (new URLSearchParams({
        "choose": "file",
        "choose_callback": neutron.winid,
        "choose_callback_id": "open_bg_image"
    }).toString()
    ), 0, 0)
}

function change_bg_custom_callback(filepath) { // 更改背景选择回调
    var xhr = new XMLHttpRequest();
    var url = new URLSearchParams();
    url.append("path", filepath)
    xhr.open("POST", API_PATH + "/change_bg_img?" + url.toString(), true);
    change_bg(1)
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var data = JSON.parse(xhr.responseText)
            if (data["code"] == 0) { // 切换
                change_bg(6)
                window.parent.document.getElementById("win_app").setAttribute("style", "background-image:url('" + API_PATH + "/bg_image/" + Math.random(1, 1000000) + "');background-size:cover;background-position: center;background-repeat:no-repeat;")
            } else {
                alert(data["msg"])
            }
        }
    }
    xhr.send();
}


window.addEventListener("message", winapi_receiveMessage, false);
function winapi_receiveMessage(event) { // 选择文件回调
    if (event.origin != location.origin) {
        return;
    }
    var data = event.data;
    if (data["type"] != "choose_file") {
        return
    }
    if (data["id"] == "open_bg_image") {
        filepath = data["data"]
        change_bg_custom_callback(filepath)
    }
}

function open_link() { // 打开主页
    window.open('https://gitee.com/cxy_kevin/neutron', '_blank');
}

function update() { // 更新面板
    var params = new URLSearchParams();
    params.append('cmd', "sudo bash " + PLUGIN_DIR + "/server/update.sh");
    neutron.createIframeWin("Terminal", "/api/plugin/terminal/iframe/index.html?" + params.toString()) // 打开终端
}

function power_do(power_type) { // 电源操作
    var xhr = new XMLHttpRequest();
    var url = new URLSearchParams();
    url.append("power", power_type)
    xhr.open("POST", API_PATH + "/power?" + url.toString(), true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var data = JSON.parse(xhr.responseText)
            if (data["code"] != 0) {
                alert(data["msg"])
            } else {
                if (window.parent.window.NEUTRON_TASKS_OPENED != true) { // 如果没有打开任务面板
                    neutron.createIframeWin("Tasks", "/api/plugin/tasks/iframe/index.html")
                }
            }
        }
    }
    xhr.send();
}

function show_hide_pages() { // 显示隐藏的页面
    var xhr = new XMLHttpRequest();
    xhr.open("GET", API_PATH + "/show_tools", true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var data = JSON.parse(xhr.responseText)
            if (data["code"] == 0) {
                var show_hides = data["data"]
                if (show_hides["power"]) {
                    document.getElementById("ch_page_3").classList.remove("hide")
                }
                if (show_hides["manager"]) {
                    document.getElementById("ch_page_5").classList.remove("hide")
                }
                if (show_hides["plugin"]) {
                    document.getElementById("ch_page_6").classList.remove("hide")
                }
            }
        }
    }
    xhr.send()
}

show_hide_pages()

function load_users() { // 加载用户列表
    var xhr = new XMLHttpRequest();
    xhr.open("GET", API_PATH + "/user", true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var data = JSON.parse(xhr.responseText)
            if (data["code"] == 0) {
                // 构造页面
                var users_name = data["data"];
                document.getElementById("page_5_users").innerHTML = ""
                for (var i = 0; i < users_name.length; i++) {
                    var user = users_name[i]
                    var template = `<div class="page_5_user">
                        <span>${user}</span>
                        <button type="button" class="inline_btn page_5_user_btn_remove remove_user_btn"
                            onclick="delete_user('${user}')">删除</button>
                        <button type="button" class="inline_btn page_5_user_btn"
                            onclick="change_user_permission('${user}')">权限</button>
                        <button type="button" class="inline_btn page_5_user_btn"
                            onclick="change_user_passwd('${user}')">改密</button>
                    </div>`
                    document.getElementById("page_5_users").innerHTML += template
                }
            } else {
                alert(data["msg"])
            }
        }
    }
    xhr.send();
}

function create_user() { // 创建用户
    var username = prompt("请输入用户名")
    if (username != null) {
        var passwd = prompt("请输入密码")
        if (passwd != null) {
            var xhr = new XMLHttpRequest();
            var url = new URLSearchParams();
            url.append("username", username)
            url.append("passwd", passwd)
            xhr.open("POST", API_PATH + "/user/create?" + url.toString(), true);
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var data = JSON.parse(xhr.responseText)
                    if (data["code"] != 0) {
                        alert(data["msg"])
                    } else {
                        load_users()
                    }
                }
            }
            xhr.send()
        }
    }
}

function delete_user(username) { // 删除用户
    var check_str = prompt("请再次输入用户名 \"" + username + "\" 以确认删除")
    if (check_str != username) {
        alert("用户名不匹配")
        return
    }
    var xhr = new XMLHttpRequest();
    xhr.open("POST", API_PATH + "/user/delete?" + (new URLSearchParams({
        "username": username
    })), true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var data = JSON.parse(xhr.responseText)
            if (data["code"] != 0) {
                alert(data["msg"])
            } else {
                load_users()
            }
        }
    }
    xhr.send()
}

function change_user_passwd(username) { // 管理员修改用户密码
    var passwd = prompt("请输入用户 \"" + username + "\" 的新密码")
    if (passwd == null) {
        return
    }
    var xhr = new XMLHttpRequest();
    xhr.open("POST", API_PATH + "/user/change_passwd?" + (new URLSearchParams({
        "username": username,
        "passwd": passwd
    })))
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var data = JSON.parse(xhr.responseText)
            if (data["code"] != 0) {
                alert(data["msg"])
            } else {
                alert("密码修改成功")
            }
        }
    }
    xhr.send()
}

function change_user_permission(username) { // 打开用户权限面板
    neutron.createIframeWin("Permission", ROOT_PATH + "/permission.html?" + (new URLSearchParams({
        "username": username
    }))
    )
}

function change_passwd() { // 修改用户密码
    var passwd = prompt("请输入新密码")
    if (passwd == null) {
        return
    }
    var xhr = new XMLHttpRequest();
    xhr.open("POST", API_PATH + "/change_passwd_user?" + (new URLSearchParams({
        "passwd": passwd
    })))
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var data = JSON.parse(xhr.responseText)
            if (data["code"] != 0) {
                alert(data["msg"])
            } else {
                alert("密码修改成功")
            }
        }
    }
    xhr.send()
}

function logout() { // 注销
    window.top.location.href = window.top.location.protocol + "//" + window.top.location.host + "/logout"
}

function clean_session() { // 重置会话
    window.top.location.href = window.top.location.protocol + "//" + window.top.location.host + "/clean_session"
}

function show_all_tasks() {
    neutron.createIframeWin("Tasks", "/api/plugin/tasks/iframe/index.html?showall=true")
}

function load_plugins() { // 加载插件列表
    var xhr = new XMLHttpRequest();
    xhr.open("GET", API_PATH + "/plugin", true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var data = JSON.parse(xhr.responseText)
            if (data["code"] == 0) {
                // 构造页面
                if (data["data"]["needrestart"]) { // 显示重启图标
                    document.getElementById("page_6_need_restart").style.display = "block"
                }
                var plugins_name = data["data"]["list"];
                document.getElementById("page_6_plugins").innerHTML = ""
                for (var i = 0; i < plugins_name.length; i++) {
                    var pluginname = plugins_name[i]["name"]
                    var template = `<div class="page_6_plugin">
                        <span${plugins_name[i]["disable"] ? " style=\"color:#999999;\"" : ""}>${pluginname}</span>
                        <button type="button" class="inline_btn page_6_plugin_btn_remove remove_user_btn" id="delete_plugin_btn-id-${pluginname}"
                            onclick="delete_plugin('${pluginname}')">删除</button>
                            `+
                        (plugins_name[i]["disable"] ? `
                        <button type="button" class="inline_btn page_6_plugin_btn"
                            onclick="enable_plugin('${pluginname}')">启用</button>` : `
                        <button type="button" class="inline_btn page_6_plugin_btn"
                            onclick="disable_plugin('${pluginname}')">禁用</button>`) + `
                    </div>` // 需要处理disable和enable状态不同
                    document.getElementById("page_6_plugins").innerHTML += template
                }
            } else {
                alert(data["msg"])
            }
        }
    }
    xhr.send();
}

function disable_plugin(pluginname) { // 禁用插件
    var xhr = new XMLHttpRequest();
    xhr.open("POST", API_PATH + "/plugin/disable?" + (new URLSearchParams({
        "plug_name": pluginname
    })))
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var data = JSON.parse(xhr.responseText)
            if (data["code"] != 0) {
                alert(data["msg"])
            } else {
                load_plugins()
            }
        }
    }
    xhr.send()
}

function enable_plugin(pluginname) { // 启用插件
    var xhr = new XMLHttpRequest();
    xhr.open("POST", API_PATH + "/plugin/enable?" + (new URLSearchParams({
        "plug_name": pluginname
    })))
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var data = JSON.parse(xhr.responseText)
            if (data["code"] != 0) {
                alert(data["msg"])
            } else {
                load_plugins()
            }
        }
    }
    xhr.send()
}

function delete_plugin(pluginname) { // 删除插件
    var btn_elem = document.getElementById('delete_plugin_btn-id-' + pluginname)
    var rect = btn_elem.getBoundingClientRect()
    neutron.showContextMenu((ret) => {
        if (ret[0] != 0) {
            return
        }
        var xhr = new XMLHttpRequest();
        xhr.open("POST", API_PATH + "/plugin/remove?" + (new URLSearchParams({
            "plug_name": pluginname
        })))
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var data = JSON.parse(xhr.responseText)
                if (data["code"] != 0) {
                    alert(data["msg"])
                } else {
                    load_plugins()
                }
            }
        }
        xhr.send()
    }, ["确定"], rect.left, rect.top - 4)
}

function install_plugin_btn() { // 安装插件，打开文件选择器
    neutron.createIframeWin("Open", "/api/plugin/filemanager/iframe/index.html?" + (new URLSearchParams({
        "choose": "file",
        "choose_callback": neutron.winid,
        "choose_callback_id": "open"
    }).toString()
    ), 0, 0)
}

window.addEventListener("message", winapi_receiveMessage, false); // 接收选择文件回调
function winapi_receiveMessage(event) {
    if (event.origin != location.origin) {
        return;
    }
    var data = event.data;
    if (data["type"] != "choose_file") {
        return
    }
    if (data["id"] == "open") {
        install_plugin(data["data"])
    }
}

function install_plugin(file_path) { // 安装回调
    if (window.parent.window.NEUTRON_TASKS_OPENED != true) { // 如果没有打开任务面板
        neutron.createIframeWin("Tasks", "/api/plugin/tasks/iframe/index.html")
    }
    var xhr = new XMLHttpRequest();
    xhr.open("POST", API_PATH + "/plugin/install?" + (new URLSearchParams({
        "plug_file_path": file_path
    })))
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var data = JSON.parse(xhr.responseText)
            if (data["code"] != 0) {
                alert(data["msg"])
            } else {
                load_plugins()
            }
        }
    }
    xhr.send()
}
